package com.edu.lawdoc.validator;

import com.jfinal.kit.PathKit;

import java.io.*;

public class ValidatorEnv {

    /**
     * 在idea环境下启动，PathKit.getWebRootPath()的返回值是
     * 项目目录/src/main/webapp
     *
     * 实际部署环境是
     * 项目目录/webapp
     */
    public static void publishJs() {
        String directory = PathKit.getWebRootPath()
                + File.separator + "js"
                + File.separator + "hxValidator";
        String jsFileName = "hxValidator.js";

        File file = new File(directory);
        if(!file.exists()) {
            file.mkdirs();
        }


        try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(jsFileName);
             OutputStream out = new FileOutputStream(new File(file.getPath() + File.separator + jsFileName))){
            byte[] buffer = new byte[128];
            int len;

            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }

        file = new File(directory
                + File.separator + jsFileName);

        if(!file.exists()) {
            throw new IllegalStateException("Publish hxValidator.js failed.");
        }
    }

}
